/**
 * 
 */
package com.yinhai.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yinhai.adapter.MessageBoxListAdapter;
import com.yinhai.model.MessageBean;

/**
 * 短信详情列表
 * 
 * @author Juyon
 * 
 */
public class MessageBoxListFragment extends Fragment {
	String SENT_SMS_ACTION = "SENT_SMS_ACTION";
	private ListView talkView;
	private SimpleDateFormat sdf;
	private AsyncQueryHandler asyncQuery;
	private List<MessageBean> messages = null;
	private EditText smsContent;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.message_list_view, null);
		sdf = new SimpleDateFormat("MM-dd HH:mm");
		Bundle bundle = this.getArguments();
		String thread = bundle.getString("threadId");
		init(thread, view);
		return view;
	}

	private void init(String thread, View view) {
		TextView textView = (TextView) view.findViewById(R.id.head_title);
		textView.setText(this.getArguments().getString("address"));

		smsContent = (EditText) view.findViewById(R.id.sms_content);
		// 短信发送
		view.findViewById(R.id.sms_send).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (smsContent.getText().toString().trim().equals("")) {
					Toast.makeText(getActivity(), "请填写短信内容", Toast.LENGTH_SHORT).show();
					return;
				}
				Intent sentIntent = new Intent(SENT_SMS_ACTION);
				PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0, sentIntent, 0);
				SmsManager smsManager = SmsManager.getDefault();
				List<String> divideContents = smsManager.divideMessage(smsContent.getText().toString().trim());
				for (String text : divideContents) {
					smsManager.sendTextMessage(getArguments().getString("address"), null, text, sentPI, null);
				}
				// Uri uri = Uri.parse("smsto:"+getArguments().getString("address"));
				// Intent it = new Intent(Intent.ACTION_SENDTO, uri);
				// it.putExtra("sms_body", "102");
				// getActivity().startActivity(it);
				ContentValues values = new ContentValues();
				// 发送时间
				values.put("date", System.currentTimeMillis());
				// 阅读状态
				values.put("read", 0);
				// 1为收 2为发
				values.put("type", 2);
				// 送达号码
				values.put("address", getArguments().getString("address"));
				// 送达内容
				values.put("body", smsContent.getText().toString().trim());
				// 插入短信库
				getActivity().getContentResolver().insert(Uri.parse("content://sms/sent"), values);
				smsContent.setText("");
				query();
			}
		});

		talkView = (ListView) view.findViewById(R.id.message_list);
		messages = new ArrayList<MessageBean>();
		query();

		// register the Broadcast Receivers
		getActivity().registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context _context, Intent _intent) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getActivity(), "短信发送成功", Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					break;
				}
			}
		}, new IntentFilter(SENT_SMS_ACTION));

	}

	private void query() {
		asyncQuery = new MessageAsynQueryHandler(this.getActivity().getContentResolver(), this.getActivity());
		Uri uri = Uri.parse("content://sms");
		String[] projection = new String[] { "date", "address", "person", "body", "type","_id" }; // 查询的列
		asyncQuery.startQuery(0, null, uri, projection, "thread_id = " + this.getArguments().getString("threadId"),
				null, "date asc");
	}

	private class MessageAsynQueryHandler extends AsyncQueryHandler {
		private Context contextt;

		public MessageAsynQueryHandler(ContentResolver cr, Context context) {
			super(cr);
			contextt = context;
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (messages != null && !messages.isEmpty()) {
				messages.clear();
				((MessageBoxListAdapter) (talkView.getAdapter())).notifyDataSetChanged();
			} else {
				messages = new ArrayList<MessageBean>();
			}
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					String date = sdf.format(new Date(cursor.getLong(cursor.getColumnIndex("date"))));
					if (cursor.getInt(cursor.getColumnIndex("type")) == 1) {
						MessageBean d = new MessageBean(cursor.getString(cursor.getColumnIndex("address")), date,
								cursor.getString(cursor.getColumnIndex("body")), R.layout.list_say_he_item,cursor.getString(cursor.getColumnIndex("_id")));
						messages.add(d);
					} else {
						MessageBean d = new MessageBean(cursor.getString(cursor.getColumnIndex("address")), date,
								cursor.getString(cursor.getColumnIndex("body")), R.layout.list_say_me_item,cursor.getString(cursor.getColumnIndex("_id")));
						messages.add(d);
					}
				}
				if (messages.size() > 0) {
					talkView.setAdapter(new MessageBoxListAdapter(contextt, messages));
					talkView.setDivider(null);
					talkView.setSelection(messages.size());
				} else {
					Toast.makeText(contextt, "没有短信进行操作", Toast.LENGTH_SHORT).show();
				}
			}
			super.onQueryComplete(token, cookie, cursor);
		}
	}
}
